<?php

namespace app\http\controller\admin\sys\auth;

use FApi\Route;
use app\model\AuthRuleModel;
use app\http\controller\admin\Controller;

/**
 * 权限规则控制器
 */
class RuleController extends Controller
{
    /**
     * 路由规则管理
     *
     * @return void
     */
    public function index(AuthRuleModel $model)
    {
        if ($this->request->isAjax()) {
            return $this->success('ok', $model->getTreeList('*', 'title', []));
        }
        return $this->fetch('sys/auth/rule/index');
    }

    /**
     * 新增
     *
     * @param AuthRuleModel $model
     * @return void
     */
    public function add(AuthRuleModel $model)
    {
        if ($this->request->isPost()) {
            $option = $this->request->post();
            $edit = $model->add($option);
            if (!$edit) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }
        // 输出规则树select
        $rule = $model->getTreeList();
        array_unshift($rule, ['id' => 0, 'title' => '无', 'pid' => 0]);
        $selected = $this->request->get('idx', 0);
        $this->assign('rule', $rule);
        $this->assign('selected', [intval($selected)]);
        return $this->fetch('sys/auth/rule/add');
    }

    /**
     * 编辑
     *
     * @return void
     */
    public function edit(AuthRuleModel $model)
    {
        $id = $this->request->get('idx');
        if (!$id) {
            return $this->error('参数错误');
        }
        // 查询规则
        $data = $model->getInfo(['id' => $id]);
        if (!$data) {
            return $this->error($model->getError());
        }
        // post更新操作
        if ($this->request->isPost()) {
            $option = $this->request->post();
            $option['idx'] = $id;
            $edit = $model->edit($option);
            if (!$edit) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }

        $rule = $model->getTreeList();
        array_unshift($rule, ['id' => 0, 'title' => '无', 'pid' => 0]);
        $this->assign('rule', $rule);
        $this->assign('data', $data);
        return $this->fetch('sys/auth/rule/edit');
    }

    /**
     * 发布路由缓存
     *
     * @return void
     */
    public function publish()
    {
        $cache = Route::instance()->cache(ROUTE_CACHE);
        if (!$cache) {
            return $this->error('路由规则发布失败，请检查缓存目录是否可写');
        }

        return $this->success('操作成功');
    }
}
